const {
    Wechaty,
    Message,
    MediaMessage,
    Room,
    Contact,
    FriendRequest
} = require('wechaty')

const bot = Wechaty.instance();

const {
    getContact,
    getRoom,
    log,
    sendMediaMsg
} = require('./util')

let MyGroupHashKey = "01C"
let MyRoomName = "叶鸟人生日快乐"

let allMsg = []

bot.start();

// 获取二维码
bot.on('scan', (url, code) => {

    if (!/201|200/.test(String(code))) {
        let loginUrl = url.replace(/\/qrcode\//, '/l/')
        require('qrcode-terminal').generate(loginUrl)
    }

    log(`登陆二维码: ${code} \n ${url}`)
})

// 监听用户登录成功
bot.on('login', async user => {

    log(`用户 ${user} 已经登陆了`);
})

bot.on("message", async msg => {

    let room = await msg.room();
    const from = await msg.from()
    const msgType = await msg.type()
    const content = await msg.content()
    const self = await msg.self()
    const topic = room && room.topic()

    log(`${content}---${msg.type()}--`)

    //return;

    // log(`
    //     消息来自好友:---${await from.name()} \n
    //     消息来自群聊:---${await room.topic()} \n
    //     消息内容:---${msg.content()} \n
    //     消息类型：---type:${msg.type()}----typeSub:${msg.typeSub()}----typeEx:${msg.typeEx()}
    // `)

    // 保存群聊，而且是 名字为11 的群聊,不是自己的
    if (room && (topic == "11"||topic==MyRoomName) && !self) {
        allMsg.push({
            name: from.name(),
            content: content
        })
    }

    // 手动更新群名字
    if (/^URN/i.test(content) && self) {
        let rName = content.split("URN-")[1];

        //room=await room.refresh();
        MyRoomName = rName;

        log(`手动更新群名字 ----------${MyRoomName}`)
    }
    

    const roomName = await room.topic();

    // log(`
    //     消息来自群聊:---${roomName} \n
    //     updateRoomName----${MyRoomName} \n
    //     消息类型：---type:${msg.type()}----typeSub:${msg.typeSub()}----typeEx:${msg.typeEx()}
    // `)


    // 发送 C 获取联系人的 hashkey
    if (/^C/i.test(content) && self) {

        let contactName = content.split("C-")[1]
        let contact = await getContact(contactName)

        contact = contact[0]

        const hashKey = contact.rawObj.$$hashKey

        await log(`联系人--------->`, contact)

        await room.say(`联系人 ${await contact.name()} hashKey-----${hashKey}`)

        //log(`ID`, ID) SPANCLASSEMOJIEMOJI1F436SPANNIANKUAIYUE

    }

    // 发送 Q 获取群聊的 hashkey
    else if (/^Q/i.test(content) && self) {

        let rName = content.split("Q-")[1]
        let room = await getRoom(rName)

        room = room[0]

        log(`群聊------------>`, room)

        const hashKey = room.rawObj.$$hashKey;


        await room.say(`群聊 ${await room.topic()} $$hashKey  ${hashKey}`)

    }

    // 消息撤回    
    else if (/^wi/i.test(content) && self && msgType==1) {

        let ch_person = content.split("wi")

        let ch_person_content = ch_person[1];

        let ch_person_arr = ch_person_content.split("@"); // 不输入 @ 那么就是默认获取一条并且是倒数第一条
        let ch_person_name = ch_person_arr[0]||"醉尘"; // 撤回人的名字
        let ch_person_scope = ch_person_arr[1] || "";  // 撤回的消息范围

        let scope_arr = ch_person_scope.split(",") 
        let start = (scope_arr[0]||1)-1; // 起始位置：默认获取最后一条，从 0 开始算起的，但是发送是从1 开始，所以减1
        let len = scope_arr[1] || 1 // 条数：默认读取一条

        // 筛选出某个人的信息，并且倒序
        let ch_person_msg = allMsg.filter(person => {
            return person.name == ch_person_name
        }).reverse().slice(start, start + len)||[]
        
        try {
            // 返回撤回的消息
            for (let i = 0; i < len; i++) {
                await room.say(`${ch_person_name} 撤回了消息:  ${ch_person_msg[i].content}`)
            }
        } catch (error) {
            await room.say(`${ch_person_name} 没有这条撤回消息`)
        }

    }

    // 关闭机器人
    else if (/^quit$/i.test(content) && self) {

        bot.quit();

    }

    // 退出登录机器人
    else if (/^logout$/i.test(content) && self) {

        bot.logout();
    }

    //await dealMsg(msg)

})

bot.on("room-topic", async(room, topic, oldTopic, changer) => {


    log(`新群名-${topic}---老群名-${oldTopic}`)

    await room.refresh()

})

// 处理消息
async function dealMsg(msg) {

    const room = await msg.room();
    const from = await msg.from();
    const roomName = await room.topic();
    const isSelf = await msg.self();
    const content = await msg.content()
    const type = await msg.type()
    const fromName = await from.name()
    const hashKey = room.rawObj.$$hashKey;

    log(`roomID------------${hashKey}---\n`, room.rawObj.$$hashKey == MyGroupHashKey)

    // 指定一个群，并且不是我发的消息
    if (room && roomName == MyRoomName && !isSelf) {

        if (type != 1) {


            await room.say(`${fromName} 发了消息`)
            await msg.forward(room)
            //room.say(sendMediaMsg(msg.readyStream()))
            //room.say(msg.readyStream())

        } else {
            await room.say(`${fromName} 发了消息： ${content}`)
        }

    }
}

async function showFileDetail(msg) {

    log(`文件后缀:---${msg.ext()}`)
    log(`文件名字:---${msg.filename()}`)
    log(`文件流:---${msg.readyStream()}`)
}

async function safeFile(msg) {
    log(`保存文件:---${msg.saveFile(__dirname+"/img/"+msg.filename())}`)

}